# -*- coding: utf-8 -*-
from __future__ import absolute_import

from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QTabWidget
from PyQt4.QtGui import QFileDialog
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QMessageBox

from PyQt4.QtCore import SIGNAL
from PyQt4.QtCore import QSettings
from PyQt4.QtCore import QString
from PyQt4.QtCore import QDateTime

from PyQt4.QtWebKit import QWebInspector

from ninja_ide import resources
from ninja_ide.core import settings
from ninja_ide.core import file_manager
from ninja_ide.gui.explorer import tree_projects_widget
from ninja_ide.gui.explorer import tree_symbols_widget
from ninja_ide.gui.dialogs import wizard_new_project


__explorerContainerInstance = None


def ExplorerContainer(*args, **kw):
    global __explorerContainerInstance
    if __explorerContainerInstance is None:
        __explorerContainerInstance = __ExplorerContainer(*args, **kw)
    return __explorerContainerInstance


class __ExplorerContainer(QTabWidget):

    def __init__(self, parent=None):
        QTabWidget.__init__(self, parent)
        self.setTabPosition(QTabWidget.East)
        self._ide = parent

        #Searching the Preferences
        self._treeProjects = None
        if settings.SHOW_PROJECT_EXPLORER:
            self._treeProjects = tree_projects_widget.TreeProjectsWidget()
            self.addTab(self._treeProjects, self.tr('Projects'))
            self.connect(self._treeProjects, SIGNAL("runProject()"),
                self._ide._actions._execute_project)
        self._treeSymbols = None
        if settings.SHOW_SYMBOLS_LIST:
            self._treeSymbols = tree_symbols_widget.TreeSymbolsWidget()
            self.addTab(self._treeSymbols, self.tr('Symbols'))
        self._webInspector = None
        if settings.SHOW_WEB_INSPECTOR:
            self._inspector = WebInspector(self)
            self.addTab(self._inspector, self.tr("Web Inspector"))
            self.connect(self._inspector.btnDock, SIGNAL("clicked()"),
                self._dock_inspector)

        #Now we see if there is any tab, if there is not, we hide the widget
        if self.count() == 0:
            self.hide()

    def _dock_inspector(self):
        if self._inspector.parent():
            self._inspector.btnDock.setText(self.tr("Dock"))
            self._inspector.setParent(None)
            self._inspector.resize(500, 500)
            self._inspector.show()
        else:
            self.addTab(self._inspector, self.tr("Web Inspector"))
            self._inspector.btnDock.setText(self.tr("Undock"))

    def add_tab(self, widget, name, icon):
        self.addTab(widget, QIcon(icon), name)

    def rotate_tab_position(self):
        if self.tabPosition() == QTabWidget.East:
            self.setTabPosition(QTabWidget.West)
        else:
            self.setTabPosition(QTabWidget.East)

    def show_project_tree(self):
        if self._treeProjects:
            self.setCurrentWidget(self._treeProjects)

    def show_symbols_tree(self):
        if self._treeSymbols:
            self.setCurrentWidget(self._treeSymbols)

    def show_web_inspector(self):
        if self._inspector:
            self.setCurrentWidget(self._inspector)

    def refresh_inspector(self):
        if self._inspector:
            self._inspector._webInspector.hide()
            self._inspector._webInspector.show()

    def set_inspection_page(self, page):
        if self._inspector:
            self._inspector._webInspector.setPage(page)
            self._inspector._webInspector.setVisible(True)

    def open_project_folder(self, folderName=''):
        if not self._treeProjects:
            QMessageBox.information(self, self.tr("Projects Disabled"),
                self.tr("Project support has been disabled from Preferences"))
            return
        if not folderName:
            folderName = unicode(QFileDialog.getExistingDirectory(self,
                self.tr("Open Project Directory"), settings.WORKSPACE))
        try:
            if not folderName:
                return
            elif not self._treeProjects.is_open(folderName):
                self._treeProjects.load_project(
                    file_manager.open_project(folderName), folderName)
                self.save_recent_projects(folderName)
            else:
                self._treeProjects._set_current_project(folderName)
        except Exception, reason:
            print reason, 'open_project_folder function'
            QMessageBox.information(self, self.tr("Incorrect Project"),
                self.tr("The project could not be loaded!"))

    def create_new_project(self):
        if not self._treeProjects:
            QMessageBox.information(self, self.tr("Projects Disabled"),
                self.tr("Project support has been disabled from Preferences"))
            return
        wizard = wizard_new_project.WizardNewProject(self)
        wizard.show()

    def add_existing_file(self, path):
        if self._treeProjects:
            self._treeProjects.add_existing_file(path)

    def get_actual_project(self):
        if self._treeProjects:
            return self._treeProjects.get_selected_project_path()
        return None

    def get_project_main_file(self):
        if self._treeProjects:
            return self._treeProjects.get_project_main_file()
        return ''

    def get_opened_projects(self):
        if self._treeProjects:
            return self._treeProjects.get_open_projects()

    def open_session_projects(self, projects):
        if not self._treeProjects:
            return
        for project in projects:
            if file_manager.folder_exists(unicode(project.toString())):
                self.open_project_folder(unicode(project.toString()))

    def save_recent_projects(self, folder):
        recent_project_list = QSettings().value('recentProjects',{}).toMap()
        #if already exist on the list update the date time
        if QString(folder) in recent_project_list:
            properties = recent_project_list[QString(folder)].toMap()
            properties[QString("lastopen")] = QDateTime.currentDateTime()
            recent_project_list[QString(folder)] = properties
        else:
            recent_project_list[QString(folder)] = {"name":file_manager.get_basename(folder),"isFavorite":False,"lastopen":QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings().setValue('recentProjects',recent_project_list)

    def find_most_old_open(self):
        recent_project_list = QSettings().value('recentProjects',{}).toMap()
        listFounder = []
        for recent_project_path, content in recent_project_list.iteritems():
            listFounder.append((recent_project_path, int(content.toMap()[QString("lastopen")].toDateTime().toString("yyyyMMddHHmmzzz"))))
        listFounder = sorted(listFounder, key=lambda date: listFounder[1], reverse = True)   # sort by date last used
        return listFounder[0][0]


class WebInspector(QWidget):

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        vbox = QVBoxLayout(self)
        self._webInspector = QWebInspector(parent)
        vbox.addWidget(self._webInspector)
        self.btnDock = QPushButton(self.tr("Undock"))
        vbox.addWidget(self.btnDock)
